import { useCallback } from "react";
import { useSelector, useDispatch } from "react-redux";
import couponsApi from "../api/coupons";
import Creators from "../store/actions";

export const useCoupons = () => {
  const coupons = useSelector((state) => state.coupons);
  const dispatch = useDispatch();
  const { curPage, eachPage } = coupons;
  //获取优惠券数据
  const getCoupons = useCallback(async () => {
    const data = await couponsApi.get({ curPage, eachPage });
    dispatch(Creators.getCoupons(data));
  }, [curPage, eachPage, dispatch]);
  //修改当前页
  const setCouCurPage = useCallback(
    (curPage) => {
      dispatch(Creators.setCouCurPage({ curPage }));
    },
    [dispatch]
  );
  //修改每页条数
  const setCouEachPage = useCallback(
    (eachPage) => {
      dispatch(Creators.setCouEachPage({ eachPage }));
    },
    [dispatch]
  );
  return [coupons, { getCoupons, setCouCurPage, setCouEachPage }];
};
